# -*- coding: utf-8 -*-
# @Time    : 2021/11/11 17:04
# @Author  : ydh
# @File    : fakers.py
# @Software: PyCharm
# 爬取书籍信息存储到数据库中的脚本

import os
import sys
import time

import django
import faker
import requests
from lxml import etree

zh_faker = faker.Faker("zh_CN")
back = os.path.dirname
BASE_DIR = back(back(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BookManager.settings')
django.setup()

from apps.book.models.AuthorInfo import AuthorInfo
from apps.book.models.BookInfo import BookInfo
from apps.book.models.CategoryInfo import CategoryInfo
from apps.book.models.PubHouse import PubHouse
from apps.book.models.BookSection import BookSection


# 创建作者
def create_author(contents, i):
    try:
        authors = contents[i]["book_author"].split("、")
        for author in authors:
            faker_author = AuthorInfo(
                auhtor_name=author,
            )
            faker_author.save()
    except Exception as e:
        print("失败")


def create_book(contents):
    pass


def create_category(contents):
    pass


def create_pub(contents):
    pass


def claw_book():
    # 爬取清华大学出版社的图书
    url = "http://www.tup.tsinghua.edu.cn/booksCenter/booklist.html?keyword=python&keytm=8E393F209188936A8D"
    etree_html = etree.HTML(requests.get(url).text)
    # 获取图书：
    for i in range(1, 16):
        book_name = etree_html.xpath(f'//*[@id="csproduct"]/li[{i}]/a/span')[0].attrib.get('title')
        book_author = etree_html.xpath(f'//*[@id="csproduct"]/li[{i}]/a/p[1]/text()')[0]
        book_isbn = etree_html.xpath(f'//*[@id="csproduct"]/li[{i}]/a/p[2]/text()')[0]
        book_price = etree_html.xpath(f'//*[@id="csproduct"]/li[{i}]/a/p[3]/text()')[0]
        book_cover = 'http://www.tup.tsinghua.edu.cn' + etree_html.xpath(f'//*[@id="csproduct"]/li[{i}]/a/img/@src')[0]
        url_html = 'http://www.tup.tsinghua.edu.cn/booksCenter/' + etree_html.xpath(f'//*[@id="csproduct"]/li[{i}]/a/@href')[0]
        book_etree_html = etree.HTML(requests.get(url_html).text)
        book_desc = book_etree_html.xpath(f'/html/body/div[2]/div[1]/div[2]/div[2]/div[1]/p/text()')[0].replace("\r\n", "").replace(" ", "")
        contents = {
            "book_name": book_name,
            "book_author": book_author,
            "book_isbn": book_isbn,
            "book_price": book_price,
            "book_pub": "清华大学出版社",
            "book_desc": book_desc,
            "book_cover": book_cover.replace("..", ""),
        }
        print(contents)
        with open() as file:
            file.write()
        try:
            # 创建作者
            my_author = AuthorInfo(
                author_name=contents["book_author"],
                author_nationality="[中]",
            )
            my_author.save()
            # 创建图书数据
            my_book = BookInfo(
                book_name=contents["book_name"],
                book_ISBN=contents["book_isbn"],
                book_des=contents["book_desc"],
                book_price=contents["book_price"],
                book_version=1,
                book_cover=contents["book_cover"]
            )
            my_book.save()
            my_book.book_category = CategoryInfo.objects.get(id=1)
            my_book.book_pub_house = PubHouse.objects.get(id=1)
            my_book.book_author.add(my_author)
            my_book.save()
        except Exception as e:
            print(f"失败{e}")
    return None


def claw_section():
    """添加章节到book"""
    qs_book = BookInfo.objects.get(id=1)
    qs_book = BookSection.objects.get()


class pretty_fish:
    def pretty(self, head):
        pass


"""
 a = 'pwwkenw'
"""

"""
9
cap
to
cat
card
two
too
up
boat
boot
"""
